package com.my.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.my.reggie.common.R;
import com.my.reggie.pojo.User;
import com.my.reggie.service.UserService;
import com.my.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        // 获取邮箱号
        String phone = user.getPhone();
        if (phone == null) {
            return R.error("邮箱号为空！");
        }
        // 随机生成4位验证码
        String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
        log.info("验证码为：{}", code);
        //发送验证码到邮箱
        // SendEmailUtils.sendAuthCodeEmail(phone,code);

        // 将验证码保存到session
        // session.setAttribute("code", code);

        //将验证码缓存到Redis(有效时间为1分钟)
        stringRedisTemplate.opsForValue().set("code",code,1, TimeUnit.MINUTES);
        //将手机号保存到session
        session.setAttribute("phone",phone);
        return R.success("验证码发送成功！");
    }

    /**
     * 登录功能
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        // 获取手机号
        String phone = map.get("phone");
        // 获取验证码
        String code = map.get("code");
        // 从session中获取验证码
        // String codeInSession = (String) session.getAttribute("code");

        // 从缓存中获取验证码
        String codeInRedis = stringRedisTemplate.opsForValue().get("code");
        //从session中获取请求验证码的手机号
        String phoneInSession = (String) session.getAttribute("phone");
        // 进行验证码比对
        if (codeInRedis == null || phoneInSession == null || !codeInRedis.equals(code) || !phoneInSession.equals(phone)) {
            return R.error("验证码错误");
        }
        // 判断该用户是否注册
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User user = userService.getOne(lqw);
        if (user == null) {
            // 用户还未注册，自动注册
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        //设置session
        session.setAttribute("user", user.getId());
        session.setMaxInactiveInterval(6*60*60);
        //删除验证码缓存
        stringRedisTemplate.delete("code");
        return R.success(user);
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        //清除session
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("phone");
        // request.getSession().removeAttribute("code");
        return R.success("退出登录成功");
    }
}
